#!/bin/bash
ScriptPath="$( cd "$(dirname "$BASH_SOURCE")" ; pwd -P )"
# 解析命令行参数
options=$(getopt -o n:g:hd --long name:,gender:,helpc,debug -- "$@")
eval set -- "$options"
# 提取选项和参数
while true; do
  case $1 in
    -n | --name) shift; name=$1 ; shift ;;
    -g | --gender) shift; gender=$1 ; shift ;;
    -h | --helpc) helpc=true ; shift ;;
    -d | --debug) debug=true; shift ;;
    --) shift ; break ;;
    *) echo "Invalid option: $1" exit 1 ;;
  esac
done


if [ "$helpc" = true ];then
  echo "-h | --help  print build_sh command"
  echo "-n | --name  print command Operator name"
  echo "-d | --debug print Build Type ,default Release"
  exit 1
fi

function main()
{
  echo "[INFO] Sample preparation"

  if [ -d ${ScriptPath}/../out/build ];then
    rm -rf ${ScriptPath}/../out/build
  fi

  if [ -z "$name" ]; then
    echo "[INFO] Author --> Hansan"
  else
    echo "[INFO] Author --> $name"
  fi

  if [ "$debug" = true ];then
    echo "[INFO] Build --> debug"
    mkdir -p ${ScriptPath}/../out/build/debug
    cd ${ScriptPath}/../out/build/debug
    cmake ../../../ -DCMAKE_CXX_COMPILER=g++ -DCMAKE_SKIP_RPATH=TRUE -DCMAKE_BUILD_TYPE=Debug
  else
    echo "[INFO] Build --> Release"
    mkdir -p ${ScriptPath}/../out/build/release
    cd ${ScriptPath}/../out/build/release
    cmake ../../../ -DCMAKE_CXX_COMPILER=g++ -DCMAKE_SKIP_RPATH=TRUE
  fi
  if [ $? -ne 0 ];then
    echo "[ERROR] cmake error, Please check your environment!"
    return 1
  fi
  make -j8
  if [ $? -ne 0 ];then
    echo "[ERROR] build failed, Please check your environment!"
    return 1
  fi
  make install -j8
  if [ $? -ne 0 ];then
    echo "[ERROR] build install failed, Please check your environment!"
    return 1
  fi
  cd - > /dev/null
  echo "[INFO] Sample preparation is complete"
}
main